/*
 * Copyright (C) 2017 yixun All Rights Reserved.
 * 
 * SmsHistoryController.java
 */
package com.yixun.qfbao.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.yixun.qfbao.model.enums.SendStatusEnum;
import com.yixun.qfbao.util.SMSUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yixun.common.controller.BaseController;
import com.yixun.common.page.Page;
import com.yixun.common.page.PageUtil;
import com.yixun.common.exception.YIXUNUNCheckedException;
import com.yixun.common.exception.YIXUNExceptionCode;
import com.yixun.qfbao.model.dto.SmsHistoryDto;
import com.yixun.qfbao.controller.vo.SmsHistoryVo;
import com.yixun.qfbao.service.SmsHistoryService;
import com.yixun.qfbao.model.SmsHistory;

/**
 * [文件名称]<br>
 * SmsHistoryController.java<br>
 * <br>
 * [文件描述]<br>
 * 消息历史 Controller<br>
 * <br>
 * [修改记录]<br>
 * 2017-05-04 10:48:27 创建 陶俊代码生成器<br>
 * 
 * @author 陶俊代码生成器
 * @version 1.00
 */
@Controller
@RequestMapping("/channel/smshistory")
public class SmsHistoryController extends BaseController {
	@Autowired
	private SmsHistoryService mservice;
	@Autowired
	private SMSUtil smsUtil;
	private static Logger log = Logger.getLogger(SmsHistoryController.class);
	
	@RequestMapping({"/manage"})
	public String index(Model model){
		return "channel/smshistory/manage";
	}
	
	@RequestMapping("/list")
	public @ResponseBody Page<SmsHistory> indexJson(SmsHistoryVo entity,HttpServletResponse response,int page,int rows){
		Page<SmsHistory> pageModel = null;
		try {
			pageModel = mservice.getPageModel(entity.toDto(),PageUtil.begin(page,rows),PageUtil.end(page,rows));
		}catch (YIXUNUNCheckedException e) {
			log.error("分页信息失败: {}",e);
			pageModel = new Page<SmsHistory>();
			pageModel.setErrorMsg(e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("分页信息失败: {}",e);
			pageModel = new Page<SmsHistory>();
			pageModel.setErrorMsg(YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return pageModel;
	}
	
	@RequestMapping("/view")
	public String formView(Model model,SmsHistoryVo entity,HttpServletResponse response,Boolean isBack) throws IOException{
		try {
			if(isBack!=null&&isBack.booleanValue()){
				model.addAttribute("model",entity);
			}else{
				model.addAttribute("model",mservice.selectById(entity.getId()));
			}
		}catch (YIXUNUNCheckedException e) {
			log.error("创建失败: {}",e);
		}catch (Exception e) {
			log.error("创建失败: {}",e);
		}
		return "/channel/smsHistory/save_edit";
	}
	
	@RequestMapping("/save_edit")
	public String saveOrUpdate(Model model,SmsHistoryVo entity,HttpServletResponse response) throws IOException{
		String errorMsg = null;
		try {
			mservice.saveOrUpdate(entity);
		}catch (YIXUNUNCheckedException e) {
			log.error("编辑失败: {}",e);
			errorMsg = e.getCode()+":"+e.getOutMsg();
		}catch (Exception e) {
			errorMsg = YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout();
			log.error("编辑失败: {}",e);
		}
		if(StringUtils.isNotBlank(errorMsg)){
			model.addAttribute("errorMsg", errorMsg);
			return formView(model,entity,response,true);
		}
		return "forward:manage";
	}
	
	@RequestMapping("/del")
	public @ResponseBody Map<String,Object> destroy(SmsHistoryVo entity,HttpServletResponse response) throws IOException{
		Map<String,Object> res = new HashMap<String, Object>();
		try {
			int destroyCount = mservice.destroy(entity.toDto());
			res.put("count",destroyCount);
			res.put("row",entity.toDto());
		}catch (YIXUNUNCheckedException e) {
			log.error("删除失败: {}",e);
			res.put("errorMsg",e.getCode()+":"+e.getOutMsg());
		}catch (Exception e) {
			log.error("删除失败: {}",e);
			res.put("errorMsg",YIXUNExceptionCode.UNKNOW_EXCEPTON.getDesout());
		}
		return res;
	}
	
	@RequestMapping({"/smsSummaryManage"})
	public String smsSummaryManage(Model model){
		return "/channel/smshistory/smsSummaryManage";
	}

	@RequestMapping("/smsSummary")
	public @ResponseBody List<SmsHistoryDto> smsSummary(SmsHistoryVo entity,HttpServletResponse response){
		List<SmsHistoryDto> smsHisDtoList = new ArrayList<SmsHistoryDto>();
		try {
			smsHisDtoList = mservice.getSmsSummary(entity.toDto());
		}catch (YIXUNUNCheckedException e) {
			log.error("短信发送统计数据获取失败: {}",e);
		}catch (Exception e) {
			log.error("短信发送统计数据获取失败: {}",e);
		}
		return smsHisDtoList;
	}

	@RequestMapping({"/smsFailureManage"})
	public String smsFailureManage(Model model){
		return "/channel/smshistory/smsFailureManage";
	}

	@RequestMapping("/smsFailureList")
	public @ResponseBody Page<SmsHistoryDto> smsFailureList(SmsHistoryVo entity, HttpServletResponse response, int page, int rows){
		Page<SmsHistoryDto> smsHisDtoList = null;
		try {
			smsHisDtoList = mservice.getSmsFailurePage(entity.toDto(), PageUtil.begin(page,rows),PageUtil.end(page,rows));
		}catch (Exception ex) {
			log.error("获取短信发送失败记录错误: {}", ex);
		}
		return smsHisDtoList;
	}

	@RequestMapping("/sendSmsAgain")
	public @ResponseBody Map<String, String> sendSmsAgain(@Param("id") String id){
		Map<String, String> result = new HashMap<String, String>();
		SmsHistory history = mservice.selectById(Long.valueOf(id));
		if(null != history){
			String repeatCount = history.getRepeatCount();
			String repeatStatus = history.getRepeatStatus() == null ?"0":history.getRepeatStatus();
			int currRepeatCount = 0;
			if(StringUtils.isNotBlank(repeatCount)){
				currRepeatCount = Integer.parseInt(repeatCount);
				if("1".equals(repeatStatus) || null != history.getOriginalId()){
					//代表发送次数过多,不予处理
					result.put("sendMsg", "发送次数过多");
					return result;
				}
			}
			currRepeatCount += 1;
			//發送短信.采用第一信息的通道进行补发
			//原因: 没有好用的且有钱的通道.
			Map<String, Object> returnMap = smsUtil.sendMessage(history.getContent(), history.getReceiver(), null, null, null);
			boolean sendStatus = (Boolean) returnMap.get("sendStatus");
			String sendRes = String.valueOf(returnMap.get("sendRes"));

			//保存短信历史信息
			SmsHistoryDto smsHis = new SmsHistoryDto();
			smsHis.setSender(smsUtil.getUserName());
			smsHis.setSender("qiaofang");
			smsHis.setReceiver(history.getReceiver());
			smsHis.setContent(history.getContent());
			smsHis.setSendStatus(sendStatus? SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
			smsHis.setSendRes(sendRes);
			smsHis.setOriginalId(history.getId());
			smsHis.setRepeatCount(String.valueOf(currRepeatCount));
			smsHis.setMerchantId(history.getMerchantId());
			smsHis.setRemark(history.getRemark());
			smsHis.setCreateUserId(history.getCreateUserId());
			if(returnMap.containsKey("orderUuid")){
				history.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
			}
			if(returnMap.containsKey("platform")){
				smsHis.setPlatform(String.valueOf(returnMap.get("platform")));
			}
			mservice.create(smsHis);

			//修改当前短信发送次数
			smsHis = new SmsHistoryDto();
			smsHis.setId(history.getId());
			smsHis.setRepeatStatus(sendStatus?SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
			smsHis.setRepeatCount(String.valueOf(currRepeatCount));
			mservice.update(smsHis);
			result.put("sendMsg", "补发成功!");
		}
		return result;
	}
}
